/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.bifrost.common.constant.SessionConstant;
import com.bifrost.entity.Customer;
import com.bifrost.service.CustomerService;
import com.bifrost.service.MemberService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *
 *
 *@author joewee
 *@version 1.0.0
 *@Date 2018/3/19 14:12
 */
@Controller
@RequestMapping("/")
public class CbestUnionIdController {
    @Autowired
    private CustomerService customerService;
    @Autowired
    MemberService memberService;
    private static final Logger LOGGER = LoggerFactory.getLogger(CbestUnionIdController.class);
    @RequestMapping("hqopenid/{unionid}")
    public String unionid(@PathVariable("unionid")String unionid,String state, HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession(true);
        if (StringUtils.isNotEmpty(unionid)) {
            Object openId = session.getAttribute(SessionConstant.OPEN_ID);
            if(openId!=null){
                Customer customer =  customerService.findByOpenId(openId.toString());
                customer.setUnionId(unionid);
                try{
                    JSONObject json = memberService.getMemberInfo(unionid);
                    if(json.containsKey("errCode") && json.getIntValue("errCode")==0){
                        if (JSONPath.contains(json,"$.data.cardno")) {
                            String cardNo =(String) JSONPath.eval(json,"$.data.cardno");
                            if (!cardNo.equals(customer.getLoyaltyCard()) && org.apache.commons.lang.StringUtils.isNotBlank(cardNo)) {
                                if(JSONPath.contains(json,"$.data.username")){
                                    customer.setCustomerLastname(""+JSONPath.eval(json,"$.data.username"));
                                }
                                if(JSONPath.contains(json,"$.data.idno")){
                                    String idNo = ""+JSONPath.eval(json,"$.data.idno");
                                    customer.setIdentificationId(idNo);
                                    customer.setCustomerBirthday(StringUtils.substring(idNo,6,14));
                                }
                                if(JSONPath.contains(json,"$.data.tel")){
                                    customer.setCustomerPhone(""+JSONPath.eval(json,"$.data.tel"));
                                }
                                customerService.bindLoyaltyCard(customer,cardNo);
                            }
                        }
                    }
                }catch (Exception e){
                    LOGGER.error(e.getMessage(),e);
                }
                customerService.saveCustomer(customer);
                Object url = session.getAttribute(SessionConstant.REDIRECT_URL);
                if(url!=null&&StringUtils.isNoneBlank(url.toString())){
                    session.removeAttribute(SessionConstant.REDIRECT_URL);
                    return "redirect:"+url.toString();
                }
                return "redirect:/index.html";
            }
        }
        return "";
    }
}
